import { mapActions, mapState } from "vuex";

import { weixin_pay, order_change_status } from "../api/order.js";
import { my_coupon } from "../api/coupon.js";

export default {
  data() {
    return {
      order_coupon: {}, // 优惠券信息
      coupon_list: [], //优惠券列表
      order_refund: {},
    };
  },
  computed: {
    ...mapState("user", ["isLogin"]),
  },
  onShow() {
    console.error("isLogin", this.isLogin);
  },
  methods: {
    ...mapActions("food", ["set_clear_food_shop_car"]),
    ...mapActions("shop", ["set_clear_shop_shop_car"]),
    // 优惠券
    async get_my_coupon(type, goods) {
      // let data = {
      //   currentPage: 1,
      //   pageSize: 50,
      //   status: 1,
      //   orderType: type,
      // };
      // const { code, body } = await my_coupon(data);
      // if (code === "0") {
      //   this.coupon_list = body.records || [];
      //   // this.set_order_coupon();
      //   this.getTheBest(goods, this.coupon_list);
      // }
    },
    // set_order_coupon() {
    //   //获取商品列表 筛选可用优惠券列表
    //   //默认 优惠券需要大于启用金额
    //   let order_coupon =
    //     this.coupon_list.find(
    //       (item) => this.order_food_money * 1 >= item.enableFee * 1
    //     ) || {};
    //   if (order_coupon.id) {
    //     // type 1 满减 折扣
    //     if (order_coupon.type === 1) {
    //       // 满减金额直接赋值
    //       order_coupon.money =
    //         this.order_food_money > order_coupon.couponFee
    //           ? parseFloat(order_coupon.couponFee)
    //           : this.order_food_money;
    //     } else {
    //       // 折扣需要计算
    //       let money = (
    //         this.order_food_money * 1 -
    //         this.order_food_money * (order_coupon.rebate / 10)
    //       ).toFixed(2);
    //       // 折扣抵扣 最高可抵扣金额
    //       order_coupon.money =
    //         parseFloat(money) > order_coupon.upFee
    //           ? order_coupon.upFee
    //           : parseFloat(money);
    //     }
    //   }
    //   this.order_coupon = order_coupon;
    //   uni.setStorageSync("change_coupon", order_coupon);
    //   console.log("this.order_coupon", this.order_coupon);
    // },
    getTheBest(goods, tickets) {
      console.log("【开始匹配优惠券--------------------】", goods, tickets);
      if (!tickets.length) return uni.setStorageSync("change_coupon", {});
      //筛选出当前商品列表内可用优惠券
      const allCanUseList = tickets.filter(
        (v) =>
          goods.some((it) => v.goodsRelIdList.includes(it.id)) || !v.goodsRel //通用卷的情况
      );
      if (!allCanUseList?.length)
        return uni.setStorageSync("change_coupon", {});
      //匹配出所有优惠券对应的商品
      const goodsGroup = allCanUseList.reduce((pre, cur) => {
        //当前优惠券的可用商品
        let goodsItems = goods.filter((v) => cur.goodsRelIdList.includes(v.id));
        if (!cur.goodsRel) {
          //通用卷的情况
          goodsItems = goods;
        }
        pre.push({
          ticket: cur, //优惠券
          goodsValues: goodsItems, //商品s
          totalPrice: goodsItems.reduce((p, c) => {
            //计算商品总价
            p += c.price * c.number;
            return p;
          }, 0),
        });
        return pre;
      }, []);
      //二次筛选，得到所有可用优惠券，满级需要判断，折扣直接添加 1满减 2折扣
      const filterGoodsGroup = goodsGroup.reduce((pre, cur) => {
        //商品金额为0时候不需要优惠券
        if (cur.totalPrice == 0) {
          return pre;
        }
        //折扣
        if (cur.ticket.type != 1) {
          pre.push(cur);
          return pre;
        }
        //满减 总金额需要大于启用金额
        if (cur.totalPrice >= cur.ticket.enableFee) {
          pre.push(cur);
        }
        return pre;
      }, []);
      if (!filterGoodsGroup?.length) {
        console.log("【暂无可用优惠券】");
        return uni.setStorageSync("change_coupon", {});
      }
      //计算所有优惠券的优惠金额，并筛选出最优的一张
      filterGoodsGroup.forEach((v) => {
        //满减直接赋值
        if (v.ticket.type == 1) {
          v.subtractNum = v.ticket.couponFee;
        } else {
          //折扣计算
          let num = (
            v.totalPrice * 1 -
            v.totalPrice * (v.ticket.rebate / 10)
          ).toFixed(2);
          //超过最大优惠取最大优惠
          v.subtractNum =
            parseFloat(num) > v.ticket.upFee ? v.ticket.upFee : parseFloat(num);
        }
      });
      //按优惠金额从大到小排序
      const sortList = filterGoodsGroup.sort(
        (a, b) => b.subtractNum - a.subtractNum
      );
      //取最优优惠券
      const goodItem = sortList[0];
      this.order_coupon = {
        ...goodItem.ticket,
        money: goodItem.subtractNum,
      };
      uni.setStorageSync("change_coupon", this.order_coupon);
      console.log(this.order_coupon, "最优优惠券====================");
    },
    async get_wx_order(val, type) {
      const userInfo = uni.getStorageSync("userInfo");
      let data = {
        // openId: userInfo.openId,
        orderFatherId: val.id,
        orgId: val.orgId,
        payFee: val.payFee,
        receivableFee: val.receivableFee,
        payMethod: 'WX'
        // orderIdList: val.orderIdList,
      };
      //payStatus:body.payStatus, // 支付状态 0元
      if (val.payStatus == "PAID") {
        // return uni.redirectTo({
        //   url: `/pages/my/order/order?type=${val.orderId}`,
        // });
        setTimeout(() => {
          // this.set_clear(type);
          uni.redirectTo({
            url: `/pages/my/order/details?id=${val.id}`,
          });
        }, 1000);
        return;
      }
      const { code, body } = await weixin_pay(data);
      if (code === "0") {
        let pay_info = JSON.parse(body?.payInfo) || {};
        let info = {
          outTradeNo: body.outTradeNo,
          id: val.id,
        };
        this.get_wx_pay(pay_info, info, type);
        uni.setStorageSync("order_details", val, type); // 保存订单id 用于支付完成状态 跳转订单详情
      }
    },
    get_wx_pay(wx, info, type) {
      console.log("wx", wx);
      const that = this;
      uni.requestPayment({
        //微信支付
        provider: "wxpay",
        timeStamp: wx.timeStamp,
        nonceStr: wx.nonceStr,
        package: wx.packageValue,
        signType: wx.signType,
        paySign: wx.paySign,
        success(res) {
          uni.showToast({
            title: "支付成功",
          });
          setTimeout(() => {
            order_change_status({ id: info.outTradeNo })
              .then((res) => {})
              .finally(() => {
                setTimeout(() => {
                  that.set_clear(type);
                  uni.redirectTo({
                    url: `/pages/my/order/details?id=${info.id}`,
                  });
                }, 1000);
              });
          }, 2000);
        },
        fail(err) {
          uni.showToast({
            title: "支付失败",
            icon: "error",
          });
          setTimeout(() => {
            that.set_clear(type);
            uni.redirectTo({
              url: `/pages/my/order/details?id=${info.id}`,
            });
          }, 500);
        },
      });
    },
    // get_refund(val){
    // 	this.order_refund = val
    // 	this.$refs.open_popup.open()
    // },
    // set_cancel(){
    // 	this.$refs.open_popup.close()
    // },
    set_clear(type) {
      switch (type) {
        case "food":
          this.set_clear_food_shop_car();
          break;

        case "shop":
          this.set_clear_shop_shop_car();
          break;
      }
    },
    set_pay_status(val) {
      let text = "";
      // UNPAID("待支付"),
      // PAID("已支付"),
      // IN_AFTER_SALE("售后中"),
      // REFUND("已退款"),
      // FINISHED("已完成"),
      // CLOSED("已关闭"),
      switch (val) {
        case "UNPAID":
          text = "待支付";
          break;

        case "PAID":
          text = "已支付";
          break;

        case "IN_AFTER_SALE":
          text = "退款中";
          break;

        case "REFUND":
          text = "退款成功";
          break;

        case "FINISHED":
          text = "已完成";
          break;

        case "CLOSED":
          text = "已关闭";
          break;
      }
      return text;
    },
  },
};
